#include "platform.h"
#include "MultiTimer.h"
#include "SoftUart.h"
#include "SoftSPI.h"
// #include "SoftI2C.h"
#include "motor_28byj48.h"
#include "StaLed.h"

StaLed_t myled ;
// I2C_t i2c0;
SPI_t spi1 ;
Motor_28BYJ48_t m ;
MultiTimer timer1 , timer2 , timer3 , timer4 , timer5;
void timer1_cb(MultiTimer* timer, void* userData) ;
void timer2_cb(MultiTimer* timer, void* userData) ;
// void timer3_cb(MultiTimer* timer, void* userData) ;
void timer4_cb(MultiTimer* timer, void* userData) ;
void timer5_cb(MultiTimer* timer, void* userData) ; // 28byj-48 步进电机
uint32_t Platform_Tik() ;
void main()
{

    *SPI_BASEADDR = 0;
    *I2C_BASEADDR = 0 ; // 仿真时需要
    StaLed_Init(&myled , &LED) ;
    StaLed_Set(&myled,0,STALED_BLINK_MID) ;
    // SoftI2C_Init(&i2c0 ,I2C_BASEADDR, I2C0_PIN_SCL ,I2C0_PIN_SDA , 0) ;
    
    Serv_BitWrite(SPI_BASEADDR, SPI0_PIN_SELECT,1);
    SoftSpi_Init(&spi1,SPI_BASEADDR,SPI0_PIN_CLOCK, SPI0_PIN_MOSI, SPI0_PIN_MISO ,1 , 1,2);

    Motor_28BYJ48_Init(&m,MOTOR_28BYJ48_BASEADDR,4  , 65535 ) ;

    MultiTimerInstall(Platform_Tik) ;
    MultiTimerStart(&timer1, 0, timer1_cb, (void *)125);  // LED 
    MultiTimerStart(&timer2, 0 ,timer2_cb, (void *)600);  // TXD
    // MultiTimerStart(&timer3, 0 , timer3_cb, (void *)100);  // iic
    MultiTimerStart(&timer4, 0 , timer4_cb, (void *)100);  // spi
    MultiTimerStart(&timer5, 0   , timer5_cb, (void *)100);    // 28byj48 步进电机
	while(1){
        MultiTimerYield();
	}

    
	return ;
}

uint32_t Platform_Tik(){
    return TIK;
} ;
// LED指示灯 
void timer1_cb(MultiTimer* timer, void* userData) {
    // LED =~LED ;
    StaLed_Yield(&myled) ;
    MultiTimerStart(timer, (int)(int *)userData, timer1_cb, userData);
}

// 串口发送
void timer2_cb(MultiTimer* timer, void* userData) {
    for(uint8_t i=0;i<26;++i){
        TxSend('a'+i);
    }
    // for(uint8_t i=0;i<10;++i) TxSend('0'+i);

    TxSend('\r');
    TxSend('\n');
    MultiTimerStart(timer, (int)(int *)userData, timer2_cb, userData);
}

// I2C发送 
// void timer3_cb(MultiTimer* timer, void* userData) {
    // i2c 
    // SoftI2C_Start(&i2c0);
    // SoftI2C_SendByte(&i2c0,0x32); // 器件地址
    // SoftI2C_ReceiveAck(&i2c0);	
    // SoftI2C_SendByte(&i2c0,0x66); // 发送的数据
    // SoftI2C_ReceiveAck(&i2c0);	
    // SoftI2C_Stop(&i2c0);
    // MultiTimerStart(timer, (int)(int *)userData, timer3_cb, userData);
// }

// SPI 发送 
void timer4_cb(MultiTimer* timer, void* userData) {
    // Serv_BitWrite(SPI_BASEADDR, SPI0_PIN_SELECT,0);
    if(SoftSpi_Write(&spi1,0X85)) return ;
    // Serv_BitWrite(SPI_BASEADDR, SPI0_PIN_SELECT,1);
    MultiTimerStart(timer, (int)(int *)userData, timer4_cb, userData);
}

// 28byj48 步进电机 
void timer5_cb(MultiTimer* timer, void* userData) {
    Motor_28BYJ48_Walk(&m , 16 ) ;
    MultiTimerStart(timer, (int)(int *)userData, timer5_cb, userData);
}